package com.beijiteshop.shop.ui.pay

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.webkit.WebResourceRequest
import android.webkit.WebView
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import androidx.constraintlayout.widget.ConstraintLayout
import com.beijiteshop.libcommon.base.activity.BaseActivity
import com.beijiteshop.shop.R
import com.beijiteshop.shop.app.WX_PAY_REFERER
import com.beijiteshop.shop.databinding.ActivityPayBinding
import com.beijiteshop.shop.ui.main.MainActivity
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import com.just.agentweb.AgentWeb
import com.just.agentweb.WebViewClient

/**
 * @Author LiaoZhongKai
 * @Date 2021/3/12 14:35
 * @Description 支付页面
 */
class PayActivity : BaseActivity<ActivityPayBinding>() {
    companion object{

        private const val BUNDLE_PAY_URL = "bundle_pay_url"

        fun start(context: Context,url: String){
            val intent = Intent(context,PayActivity::class.java)
            intent.putExtra(BUNDLE_PAY_URL,url)
            context.startActivity(intent)
        }
    }

    private var mPayUrl: String? = null
    private var mAgentWeb: AgentWeb? = null

    override fun getLayoutRes(): Int = R.layout.activity_pay

    override fun initView(savedInstanceState: Bundle?) {
        mPayUrl = intent.getStringExtra(BUNDLE_PAY_URL)
        LogUtils.d("PAY URL :${mPayUrl}")
        mAgentWeb = AgentWeb.with(this)
            .setAgentWebParent(mBinding.payWebContainerCl,ConstraintLayout.LayoutParams(-1,-1))
            .useDefaultIndicator()
            .setWebViewClient(getWebViewClient())
            .createAgentWeb()
            .ready()
            .go(mPayUrl)
    }

    override fun initData() {

    }

    override fun initEvent() {

    }

    private fun getWebViewClient(): WebViewClient {
        return object :WebViewClient(){
            override fun shouldOverrideUrlLoading(
                view: WebView?,
                request: WebResourceRequest?
            ): Boolean {
                val url = request?.url?.toString()
                LogUtils.dTag("PAY OverrideUrlLoading url---->>:$url")
                url?.let {
                    // -----支付结果---------
                    if (it.startsWith("alipay://")){
                        val content = it.split("//")[1]
                        when(content){
                            "success" ->{
                                showPayResult(R.string.pay_success)
                                ActivityUtils.finishToActivity(MainActivity::class.java,false)
                            }
                            "fail" ->{
                                showPayResult(R.string.pay_failed)
                                finish()
                            }
                            "exception" ->{
                                showPayResult(R.string.pay_exception)
                                finish()
                            }
                            "else" ->{
                                showPayResult(R.string.pay_failed_unknown_reason)
                                finish()
                            }
                        }
                        return true
                    }

                    // ------  对alipays:相关的scheme处理 -------
                    //调用支付宝APP支付
                    if (url.startsWith("alipays:") || url.startsWith("alipay")) {
                        try {
                            startActivity(
                                Intent(
                                    "android.intent.action.VIEW",
                                    Uri.parse(url)
                                )
                            )
                        } catch (e: Exception) {
                            if (this@PayActivity == null) {
                                return true
                            }
                            if (this@PayActivity.isFinishing) {
                                return true
                            }
                            AlertDialog.Builder(this@PayActivity)
                                .setMessage("未检测到支付宝客户端，请安装后重试。")
                                .setPositiveButton(
                                    "立即安装"
                                ) { dialog, which ->
                                    val alipayUrl =
                                        Uri.parse("https://d.alipay.com")
                                    startActivity(
                                        Intent(
                                            "android.intent.action.VIEW",
                                            alipayUrl
                                        )
                                    )
                                }.setNegativeButton("取消", null).show()
                        }
                        return true
                    }

                    //调用微信APP支付
                    if (url.startsWith("weixin://")) {
                        try {
                            startActivity(
                                Intent(
                                    "android.intent.action.VIEW",
                                    Uri.parse(url)
                                )
                            )
                        } catch (e: Exception) {
                            if (this@PayActivity == null) {
                                return true
                            }
                            if (this@PayActivity.isFinishing) {
                                return true
                            }
                            AlertDialog.Builder(this@PayActivity)
                                .setMessage("未检测到微信客户端，请安装后重试。")
                                .setPositiveButton(
                                    "立即安装"
                                ) { dialog, which ->
                                    val alipayUrl =
                                        Uri.parse("https://weixin.qq.com/")
                                    startActivity(
                                        Intent(
                                            "android.intent.action.VIEW",
                                            alipayUrl
                                        )
                                    )
                                }.setNegativeButton("取消", null).show()
                        }
                        return true
                    }

                    //微信支付需要加请求头referer
                    if (url.contains("https://wx.tenpay.com")) {
                        val extraHeaders: MutableMap<String, String> = HashMap()
                        extraHeaders["Referer"] = WX_PAY_REFERER
                        view?.loadUrl(url, extraHeaders)
                        return true
                    }

                    // ------- 处理结束 -------
                    if (!(url.startsWith("http") || url.startsWith("https"))) {
                        return true
                    }

                    view?.loadUrl(url)
                }
                return true
            }
        }
    }

    private fun showPayResult(@StringRes resId: Int){
        showToast(resources.getString(resId))
    }
}